package org.javaboy.zk;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkCreateNodeDemo implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    static ZooKeeper zk;

    public static void main(String[] args) throws IOException, InterruptedException {
        zk = new ZooKeeper("s2.javaboy.org:2181", 5000, new ZkCreateNodeDemo());
        //注意，这个时候其实并没有建立连接
        ZooKeeper.States state = zk.getState();
        System.out.println("state = " + state);
        //暂停，当countDownLatch减为0的时候，程序才会继续执行
        countDownLatch.await();
    }

    public void process(WatchedEvent watchedEvent) {
        System.out.println("watchedEvent = " + watchedEvent);
        try {
            if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                System.out.println("连接成功");
                createNode();
            } else if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                System.out.println("连接断开");
            } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
                System.out.println("节点数据发生变化，即有人修改了节点的数据");
            } else if (watchedEvent.getType() == Event.EventType.NodeCreated) {
                System.out.println("节点创建成功");
            } else if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
                System.out.println("子节点发生变化");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (KeeperException e) {
            throw new RuntimeException(e);
        }
        // -1
//        countDownLatch.countDown();
    }

    private void createNode() throws InterruptedException, KeeperException {
        //创建节点，最后一个参数表示节点的类型
        String s = zk.create("/javaboy", "javaboy".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println("s = " + s);
        //查看创建的节点
        List<String> children = zk.getChildren("/", true);
        System.out.println("children = " + children);
    }
}
